<template>
  <div class="contentOuter" style="overflow-x: hidden;">
    <a-spin :spinning="spinning" tip="数据加载中，请稍后">
      <div class="stdCol bd-R pd-R of-V" style="width:20%;">
        <!-- Tree -->
        <div class="treeOut-L-tree">
          <a-button type="primary" @click="showDrawer('1')" class="treeOut-L-Add">新增{{ this.global.bomName }}</a-button>
          <a-input-search class="treeOut-L-Search" placeholder="搜索" @change="onChange" />
          <a-tree
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :tree-data="gData"
              :replace-fields="replaceFields"
              :show-line="showLine"
              :selected-keys="selectedKeys"
              @select="onSelect"
              @expand="onExpand"
          >
            <template slot="title" slot-scope="{title}">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </div>
      </div>
      <div class="stdCol pd-L of-V pd-R" style="width:80%;" v-show="detailShow">
        <div class="stdRow pd-B bd-B" style="">
          <!-- Node详情 -->
          <a-form layout="inline">
            <div class="stdRow treeForm-inputBtnGroup">
              <div class="treeForm-inputBoxTitle">
                <a-icon type="info-circle" />
                {{ this.global.bomName }}信息 {{ nowNodeCode }}
              </div>
              <a-form-item v-if="inputMode==true">
                <a-button type="Default" html-type="submit" @click="cancelChange">
                  取消修改
                </a-button>
              </a-form-item>
              <a-form-item v-if="inputMode==true">
                <a-button type="primary" html-type="submit" @click="submitChange">
                  提交修改
                </a-button>
              </a-form-item>
              <a-form-item v-if="inputMode==false">
                <a-button type="Default" html-type="submit" @click="enableEdit">
                  编辑{{ this.global.bomName }}
                </a-button>
              </a-form-item>
<!--              <a-form-item v-if="inputMode==false">-->
<!--                <a-button type="Default" @click="test()">-->
<!--                  测试-->
<!--                </a-button>-->
<!--              </a-form-item>-->
              <a-form-item v-if="inputMode==false">
                <a-button type="Default" html-type="submit" @click="showDrawer()">
                  新增子{{ this.global.bomName }}
                </a-button>
              </a-form-item>
              <a-form-item v-if="inputMode==false">
                <!-- 确认删除提醒框控件 -->
                <a-popconfirm title="删除该物料会一并删除其结构下的所有物料，确定么？"
                              ok-text="确定"
                              cancel-text="取消"
                              placement="bottomRight"
                              @confirm="deleteNode()"
                              @cancel="cancelDelete()">
                  <a-button type="danger">
                    删除{{ this.global.bomName }}
                  </a-button>
                </a-popconfirm>
              </a-form-item>
            </div>

            <div class="treeForm-inputGroup">
              <a-form-model-item v-for="item in nowNode" v-if="item.changeable===1">
                <span slot="label">{{ item.widget }}</span>
                <a-input v-model="item.value" v-bind:disabled="!inputMode" />
              </a-form-model-item>
<!--              用于判定字段类型，显示对应的格式空间-->
<!--              <a-form-model-item v-else-if="item.changeable===0">-->
<!--                <span slot="label">{{ item.widget }}</span>-->
<!--                <a-input v-model="item.value" v-bind:disabled="true" />-->
<!--              </a-form-model-item>-->
              <a-form-model-item v-else>
                <span slot="label">{{ item.widget }}</span>
                <a-input v-model="item.value" v-bind:disabled="true" />
              </a-form-model-item>
            </div>
          </a-form>
        </div>
        <div class="stdRow pd-T">
          <!-- 子表单 -->
          <div v-if="tableShow">
            <a-table
                :columns="tableCol"
                :data-source="tableData"
                :scroll="{ x: 1500 }"
                size="small"
            >
              <template slot="action" slot-scope="text,record">
                <a slot="action" @click="goToNode(record.name, record.global_code)">查看</a>
              </template>
            </a-table>
          </div>
          <a-spin :spinning="!tableShow" tip="数据加载中，请稍后" class="tableSpinning">
          </a-spin>
        </div>
      </div>
      <!-- 新增Node -->
      <a-drawer title="新增"
                :width="720"
                :visible="addOuterShow"
                :body-style="{ paddingBottom: '80px' }"
                :destroyOnClose=true
                :closable=false
      >
        <div class="addNodeClose" @click="closeAdd()"><a-icon type="close" /></div>
        <a-form layout="vertical" v-show="addShow">
          <div class="addNodeForm">
            <a-form-model-item v-for="item in newNode" v-if="item.widget_id==='local_code'">
              <span slot="label">{{ item.widget }}</span>
              <a-input v-model="item.value" v-bind:disabled="false" placeholder="未来不可修改" />
            </a-form-model-item>
            <a-form-model-item v-else-if="item.changeable===1">
              <span slot="label">{{ item.widget }}</span>
              <a-input v-model="item.value" v-bind:disabled="false" />
            </a-form-model-item>
            <a-form-model-item v-else>
              <span slot="label">{{ item.widget }}</span>
              <a-input v-model="item.value" v-bind:disabled="true" />
            </a-form-model-item>
          </div>
        </a-form>
        <div class="addNodeFormBtn" v-show="addShow">
          <a-button :style="{ marginRight: '8px' }" @click="closeAdd()" v-bind:disabled="newNodeDisable">
            取消
          </a-button>
          <a-button type="primary" @click="addNode()" v-bind:disabled="newNodeDisable">
            提交
          </a-button>
        </div>
      </a-drawer>
    </a-spin>
</div>
</template>


<script>

export default {
    data() {
      return {
        // 界面显示信息
        spinning: false, // 页面主区域loading
        detailShow: false, // 材料详情是否显示
        inputMode: false, // 是否是编辑模式
        addShow: false, // 新增表格是否展示
        addOuterShow: false, // 新增Node界面是否展示
        tableShow: false, // 表格是否展示

        // 树状结构
        expandedKeys: [], // 自动打开的节点
        searchValue: '', // 搜索字段
        showLine: true, // 显示连接线
        autoExpandParent: true, // 自动扩展爹级材料
        gData, // 树状结构数据源
        temp_gData: [], // 用于修改树状结构
        replaceFields: {
          key: 'global_code', // 更替树状结构的key
        },
        selectedKeys: [], // 选中节点
        // 本节点信息
        nowNodeCode:'', // 选中节点global_code
        nowNodeLevel:'', // 选中节点level
        nowNode: [], // 选中节点数组
        // 新增节点信息
        newNode: [], // 新增节点字段信息
        newNodeLevel: '', // 新增节点等级
        newNodeLocal: '', // 新增节点LocalCode
        newNodeBack: [], // 新增成功返回信息
        newNodeDisable: false, // 新增按钮禁用
        // 表格元素
        tableRaw: [], // 表格源数据
        tableData, // 表单内容
        tableCol, // 表头格式
        tempData: [],
        // 增删改查临时字段
        temp_name: '',
        temp_title: '',
        temp_fatherCode: '',
        temp_globalCode: '',
        title_splice: '_',
      };
    },
    mounted:
    function(){ // 页面加载触发
      this.getTree(); // 加载BOM树
      this.pageLoading(); // 页面显示加载
    },
    methods: {
      // 页面加载相关函数
      pageLoading() { // 开始加载
        this.spinning = true;
      },
      endLoading() { // 结束加载
        this.spinning = false;
      },
      logout() { // 退出登录
        localStorage.setItem("login_state",JSON.stringify(0));
        localStorage.setItem("token",""); // 更新token到本地
        this.$router.push({ path: "/login" }); // 跳转到登录
      },
      // 树状结构相关函数
      getTree() {  // API-获得树状结构
        this.pageLoading(); // 页面进入加载
        let _this = this;
        let axios = require('axios');
        let url = this.global.serverLocation + "/gettree";
        let login_token = localStorage.getItem("token");
        let data = JSON.stringify({
          "token": login_token,
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
              } else if (response.data.state === 0) {
                _this.gData = response.data.tree; // 赋值gData
                _this.generateList(_this.gData); // 更新DataList
                _this.endLoading(); // 页面结束加载
              } else if (response.data.state === 503) { // 树状结构为空
                _this.endLoading(); // 页面结束加载
                _this.gData = response.data.tree; // 赋值gData
                _this.generateList(_this.gData); // 更新DataList
              } else {
                _this.systemAlert('error','出错了',response.data.msg,10)
                _this.endLoading(); // 页面结束加载
              }
            })
            .catch(function (error) { // API错误
              console.log(JSON.stringify(error)); // 错误输出
              this.systemAlert('error','出错了',error,10)
              _this.endLoading(); // 页面结束加载
              _this.logout();
            });

      },
      onExpand(expandedKeys) { // 树状结构展开函数
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      onChange(e) { // 树状结构搜索函数
        const value = e.target.value; // 搜索值
        const expandedKeys = this.dataList
            .map(item => {
              if (item.title.indexOf(value) > -1) {
                return getParentKey(item.global_code, this.gData);
              }
              return null;
            })
            .filter(
                (item, i, self) => item && self.indexOf(item) === i
            ); //生成自动展开列表
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        });
      },
      generateList (data) { // 生成索引表
        this.dataList=[]; // 清空原有索引表
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          const global_code = node.global_code;
          const title = node.title;
          const level = node.level;
          this.dataList.push({ global_code, title, level });
          if (node.children) { // 有children触发索引子表
            this.generateSubList(node.children);
          }
        }
      },
      generateSubList (data) { // 生成索引子表
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          const global_code = node.global_code;
          const title = node.title;
          const level = node.level;
          this.dataList.push({ global_code, title, level });
          if (node.children) {
            this.generateSubList(node.children);
          }
        }
      },
      onSelect(selectedKeys) { // 树结构点击触发
        this.selectedKeys=[]; // 清空选中Node
        this.nowNodeCode = String(selectedKeys); // 获取赋值目前global_code
        this.selectedKeys.push(String(selectedKeys)); // 选中这个Node
        this.expandedKeys.push(String(selectedKeys)); // 打开这个Node
        this.getNodeLevel(this.nowNodeCode); // 获取对应Level
        this.getNodeData(); // 获取对应材料信息

      },
      // 获取Node详情相关函数
      getNodeLevel() { // 找到当前Node的level
        let e = this.nowNodeCode; // 提取当前Node的global_code
        let level = [];
        level = this.dataList.find(item => item.global_code === e);
        this.nowNodeLevel = level.level;
      },
      getNodeData() { // 材料零件获取API
        this.pageLoading(); // 页面进入加载
        this.inputMode = false; // 输入框状态复原
        this.tableShow = false; // 子表单不可见
        this.detailShow = false; // 详情不可见
        let _this = this;
        let axios = require('axios');
        let url = this.global.serverLocation + "/getnode";
        let login_token = localStorage.getItem("token");
        let data = JSON.stringify({
          "token": login_token,
          "global_code": this.nowNodeCode,
          "level": this.nowNodeLevel
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
              } else if (response.data.state === 0) {
                _this.nowNode = response.data.node; // 赋值nowNode
                _this.detailShow = true; // 显示材料详情区域
                _this.changeNodeTime(_this.nowNode); // 更新时间格式
                _this.endLoading(); // 页面结束加载
                _this.getTable();
              }
              else if(response.data.state === 502) {
                _this.systemAlert('error','操作失败',response.data.msg,10)
                _this.endLoading(); // 页面结束加载
              }
              else if (response.data.node === "") {
                _this.systemAlert('error','该数据不存在',response.data.msg,10)
                _this.endLoading(); // 页面结束加载
              }
            })
            .catch(function (error) { // API错误
              _this.systemAlert('error','API错误',JSON.stringify(error),10)
              _this.endLoading(); // 页面结束加载
            });
      },
      changeNodeTime(data) { // 修改Node日期格式
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          if (node.widget_id === "last_date") {
            node.value = this.utc2beijing(node.value);
          }
        }
      },
      utc2beijing(utc_datetime) {
        // 转为正常的时间格式 年-月-日 时:分:秒
        const T_pos = utc_datetime.indexOf('T');
        const Z_pos = utc_datetime.indexOf('Z');
        const year_month_day = utc_datetime.substr(0, T_pos);
        const hour_minute_second = utc_datetime.substr(T_pos + 1, Z_pos - T_pos - 1);
        const new_datetime = year_month_day + " " + hour_minute_second; // 2017-03-31 08:02:06
        // 处理成为时间戳
        let timestamp = new Date(Date.parse(new_datetime));
        timestamp = timestamp.getTime();
        timestamp = timestamp/1000;
        // 增加8个小时，北京时间比utc时间多八个时区
        timestamp = timestamp + 8 * 60 * 60;
        const standardDate = new Date(parseInt(timestamp) * 1000)
        var year = standardDate.getFullYear();
        var month= standardDate.getMonth()+1;
        var day = standardDate.getDate();
        var hour = standardDate.getHours();
        var minute = standardDate.getMinutes();
        var second = standardDate.getSeconds();
        var formatting = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
        return formatting;
      },
      // Node删除相关函数
      deleteNode() { // 确认删除Node
        let _this = this;
        let axios = require('axios');
        let url = this.global.serverLocation + "/deletenode";
        let login_token = localStorage.getItem("token");
        let data = JSON.stringify({
          "token": login_token,
          "global_code": this.nowNodeCode,
          "level": this.nowNodeLevel
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
              } else if (response.data.state === 0) {
                _this.systemAlert('success','删除成功','数据已经更新',3)
                _this.detailShow = false; // 隐藏界面
                _this.treeDelete(); // 在Tree中删除节点
              } else {
                _this.systemAlert('error','删除失败',response.data.msg,10)
              }
            })
            .catch(function (error) { // API错误
              _this.systemAlert('error','API错误',JSON.stringify(error),10)
            });
      },
      cancelDelete() {
        console.log("1");
      },
      // Node修改相关函数
      enableEdit() { // 编辑物料按钮
        this.inputMode = true;
      },
      submitChange() { // 提交物料按钮
        this.inputMode = false;
        let _this = this;
        let axios = require('axios');
        let url = this.global.serverLocation + "/editnode";
        let login_token = localStorage.getItem("token");
        let data = JSON.stringify({
          "token": login_token,
          "global_code": this.nowNodeCode,
          "level": this.nowNodeLevel,
          "widgets": this.nowNode
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
              } else if (response.data.state === 0) {
                _this.systemAlert('success','修改成功','数据已经更新',3)
                _this.getNodeData(); // 重新加载Node
                _this.treeChange(_this.gData); // 触发Tree修改
              } else {
                _this.systemAlert('error','修改失败',response.data.msg,10)
              }
            })
            .catch(function (error) { // API错误
              _this.systemAlert('error','API错误',JSON.stringify(error),10)
            });
      },
      cancelChange() { // 取消修改按钮
        this.getNodeData(); // 重新加载物料信息界面
        this.inputMode = false;
      },
      // 新增零件函数
      showDrawer(e) { // 新增零件
        let  level = "";
        if ( e === "1" ) {
          level = "1";
        } else {
          level = (Number(this.nowNodeLevel) + 1).toString();
        }
        this.newNodeLevel = level; // 确定新增node的level
        this.getLevelInfo(this.newNodeLevel); // 取得表单信息
        this.addOuterShow = true; // 打开新增区域
        this.newNodeDisable = false;
      },
      addNode(){
        this.newNodeDisable = true;
        let _this = this;
        let axios = require('axios');
        let url = this.global.serverLocation + "/addnode";
        let login_token = localStorage.getItem("token");
        let parentCode = '';
        if (this.newNodeLevel !== '1') {
          parentCode = this.nowNodeCode;
        }
        this.temp_fatherCode = parentCode;
        const getLocalCode = this.newNode.filter(item => item.widget_id === 'local_code');
        const newNodeCode = getLocalCode[0].value;
        let data = JSON.stringify({
          "token": login_token,
          "parent_code": parentCode,
          "local_code": newNodeCode,
          "level": this.newNodeLevel,
          "widgets": this.newNode
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
                _this.newNodeDisable = false;
              } else if (response.data.state === 0) {
                _this.systemAlert('success','新增成功2','数据已经更新',3)
                let node = response.data.node // 抽取返回的Node
                _this.newNodeBack = node.widgets; // 抽取返回的数值
                _this.treeAdd();// 修改Tree内容
                _this.addOuterShow = false;
                _this.newNodeDisable = false;
              } else {
                _this.systemAlert('error','新增失败',response.data.msg,10)
                _this.newNodeDisable = false;
              }
            })
            .catch(function (error) { // API错误
              _this.systemAlert('error','API错误2',JSON.stringify(error),10)
              _this.newNodeDisable = false;
            });
      },
      getLevelInfo(currentLevel) {
        let _this = this;
        let level = currentLevel;
        let axios = require('axios');
        let url = this.global.serverLocation + "/getlevel";
        let login_token = localStorage.getItem("token");
        let data = JSON.stringify({
          "token": login_token,
          "level": level,
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
              } else if (response.data.state === 0) {
                let node = response.data.level;
                _this.generateNewNode(node);
                _this.addShow = true;
              } else {
                _this.systemAlert('error','新增失败',response.data.msg,10)
                _this.closeAdd();
              }
            })
            .catch(function (error) { // API错误
              _this.systemAlert('error','API错误',JSON.stringify(error),10)
            });
      },
      generateNewNode (data) { // 生成新增节点数组
        this.newNode=[]; // 清空原有数组
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          const widget_id = node.widget_id;
          const widget = node.widget;
          const changeable = node.changeable;
          const value = "";
          this.newNode.push({ widget_id, widget, changeable, value });
        }
      },
      closeAdd() { // 关闭新增区域
        this.addOuterShow = false;
      },
      // 表格相关函数
      getTable() { // 材料零件获取API
        let _this = this;
        let axios = require('axios');
        let url = this.global.serverLocation + "/getchildren";
        let login_token = localStorage.getItem("token");
        let data = JSON.stringify({
          "token": login_token,
          "global_code": this.nowNodeCode,
          "level": this.nowNodeLevel
        });
        let config = {
          method: 'post',
          url: url,
          headers: {
            'Content-Type': 'application/json',
          },
          data: data
        };
        axios(config) // API结果
            .then(function (response) { // API顺利传回
              if (response.data.state === 402) {
                _this.systemAlert('error','登录过期','请重新登录',3)
                _this.logout();
              } else if (response.data.state === 0) {
                _this.tableRaw=response.data.children; // 复制表格源数据
                _this.getTableCol(_this.tableRaw); // 生成表头
                _this.getTableData(_this.tableRaw); // 生成表内容
                _this.endLoading(); // 页面结束加载
                _this.tableShow = true;
              }
              else if(response.data.msg === "子层级表单字段不存在") {
                _this.tableShow = true;
                _this.tableData = [];
                _this.tableCol = [];
                _this.tableRaw = [];
              }
              else {
                _this.tableShow = true;
                _this.tableData = [];
                _this.tableCol = [];
                _this.tableRaw = [];
                _this.systemAlert('error','子表单获取失败',response.data.msg,10)
              }
            })
            .catch(function (error) { // API错误
              _this.systemAlert('error','API错误',JSON.stringify(error),10)
              _this.endLoading(); // 页面结束加载
            });
      },
      getTableCol(data) { // 生成表格表头
        let col=data[0];
        this.tableCol=[]; // 清空原有数组
        for (let i = 0; i < col.length; i++) {
          const node = col[i];
          const widget_id = node.widget_id;
          const widget = node.widget;
          if (node.widget_id === "name") {
            this.tableCol.push({ dataIndex: widget_id, title: widget, width: 150, key: widget_id, fixed: 'left'});
          } else if (node.widget_id === "last_date") {
            this.tableCol.push({ dataIndex: widget_id, title: widget, key: widget_id, width: 200});
          } else if (node.widget_id === "global_code" || node.widget_id === "local_code" || node.widget_id === "parent_code") {
            this.tableCol.push({ dataIndex: widget_id, title: widget, key: widget_id, width: 120});
          } else {
            this.tableCol.push({ dataIndex: widget_id, title: widget, key: widget_id, width: 120});
          }
        }
        this.tableCol.push({
          title: '操作',
          dataIndex: 'action',
          key: 'UniqueKey',
          scopedSlots: { customRender: 'action' },
          width: 120,
          fixed:'right',
        });
        this.tableShow = true;
      },
      getTableData(data) {
        this.tableData=[]; // 清空原有数组
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          this.tempData={};
          for (let a = 0; a < node.length; a++ ) {
            const temp = node[a];
            const id = temp.widget_id;
            if (id === 'last_date') {
              this.tempData[id] = this.utc2beijing(temp.value);
            } else if (id === 'last_date' || id === 'local_code' || id === 'last_date') {
              this.tempData[id]=temp.value;
              this.tempData["ellipsis"]=true;
            } else {
              this.tempData[id]=temp.value;
            }

          }
          const tempData = this.tempData;
          this.tableData.push(tempData);
        }
        this.tableShow = true;
      },
      goToNode(name,code) {
        this.nowNodeCode = code; // 获取赋值目前global_code
        this.getNodeLevel(code); // 获取对应Level
        this.getNodeData(); // 获取对应材料信息
        this.selectedKeys=[]; // 清空选中的Node
        this.selectedKeys.push(code); // 选中这个Node
        this.expandedKeys.push(code); // 自动展开本Node
      },
      // showThisNode(e) { // 树状结构搜索函数
      //   const value = e; // 搜索值
      //   const expandedKeys = this.dataList
      //       .map(item => {
      //         if (item.title.indexOf(value) > -1) {
      //           return getParentKey(item.global_code, this.gData);
      //         }
      //         return null;
      //       })
      //       .filter(
      //           (item, i, self) => item && self.indexOf(item) === i
      //       ); //生成自动展开列表
      //   Object.assign(this, {
      //     expandedKeys,
      //     searchValue: value,
      //     autoExpandParent: true,
      //   });
      // },
      // 增删改对于Tree的函数
      treeChange() {
        let _this = this;
        for (let i = 0; i < this.nowNode.length; i++) { // 获得新的name
          if (this.nowNode[i].widget_id === "name") {
            this.temp_name = this.nowNode[i].value; // 赋值到辅助name字段
          }
        }
        this.temp_title = this.temp_name + this.title_splice + this.nowNodeCode; // 生成新的Title
        this.treeChangeFor(this.gData); // 触发修改执行（嵌套循环）
        this.generateList(this.gData) // 重新生成索引表
      },
      treeChangeFor(data){
        for (let i = 0; i < data.length; i++) {
          if (data[i].global_code === this.nowNodeCode) { // 如果找到了
            data[i].title = this.temp_title; // 修改title
          }
          if (data[i].children) { // 如果有儿子
            this.treeChangeFor(data[i].children);
          }
        }
      },
      treeDelete() {
        let _this = this;
        this.treeDeleteFor(this.gData); // 触发修改执行（嵌套循环）
        this.generateList(this.gData) // 重新生成索引表
      },
      treeDeleteFor(data){
        for (let i = 0; i < data.length; i++) {
          if (data[i].global_code === this.nowNodeCode) { // 如果找到了
            data[i].title = this.temp_title; // 修改title
            data.splice(i,1);
            return;
          }
          if (data[i].children) { // 如果有儿子
            this.treeDeleteFor(data[i].children);
          }
        }
      },
      treeAdd() {
        let _this = this;
        for (let i = 0; i < this.newNodeBack.length; i++) { // 获得global_code
          if (this.newNodeBack[i].widget_id === "global_code") {
            this.temp_globalCode = this.newNodeBack[i].value; // 赋值到global_code
          }
          else if (this.newNodeBack[i].widget_id === "name") {
            this.temp_name = this.newNodeBack[i].value; // 赋值到辅助name字段
          }
        }
        this.temp_title = this.temp_name + this.title_splice + this.temp_globalCode; // 组合成Title
        if ( this.temp_fatherCode === '' ) { // 如果为1级
          this.gData.push({
            global_code: this.temp_globalCode,
            title: this.temp_title,
            name: this.temp_name,
            level: this.newNodeLevel,
            children: [],
          });
        } else { // 不是1级
          this.treeAddFor(this.gData); // 触发修改执行（嵌套循环）
          this.getTable(); // 重新加载子表格
        }
        this.generateList(this.gData) // 重新生成索引表
      },
      treeAddFor(data){
        for (let i = 0; i < data.length; i++) {
          if (data[i].global_code === this.temp_fatherCode) { // 如果找到了
              data[i].children.push({
              global_code: this.temp_globalCode,
              title: this.temp_title,
              name: this.temp_name,
              level: this.newNodeLevel,
              children: [],
            });
            return;
          }
          if (data[i].children) { // 如果有儿子
            this.treeAddFor(data[i].children);
          }
        }
      }
    },
  };

  // 树状控件
  const gData = []; // 树状结构数据源
  const dataList = []; // 树状结构索引列表
  const getParentKey = (key, tree) => { // 树状结构-搜索获取爹的Code
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.global_code === key)) {
          parentKey = node.global_code;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
  // 表格控件
  const tableCol = [];
  const tableData = [];


</script>